//
//  MyDynamicViewController.m
//  Comma
//
//  Created by dlios on 15-1-13.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MyDynamicViewController.h"
#import "MyDynamicView.h"
#import "GlobalMethod.h"
#import "PersonalCenterViewController.h"
#import "AFNetWorkingYU.h"
#import "URLMacro.h"
#import "MyDynamicModel.h"
#import "DetailViewController.h"
#import "YRSideViewController.h"
#import "DetailModel.h"
#import "LoadIndicator.h"
#import "Reachability.h"
@interface MyDynamicViewController ()

@end

@implementation MyDynamicViewController

//数组  或者只要是带有self 的初始化 都要在loadView里进行初始化

- (void)loadView
{
    self.myDynamic = [[MyDynamicView alloc] initWithLeftButton:@"" RightButton:nil Title:@"我的动态" FooterView:FooterViewStateNone];
    self.view = self.myDynamic;
    self.myDynamic.delegate = self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    YRSideViewController * sideview = [YRSideViewController share];
    sideview.needSwipeShowMenu= YES;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.myDynamic createMyDynamic];
    [self.myDynamic.leftButton addTarget:self action:@selector(myLeftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self getUserIdFromSever];
}

//tableview传值Push到下一个界面（在这里标记信息留言已读）
- (void)transferModel:(MyDynamicModel *)model otherDic:(NSDictionary *)otherDic
{

    DetailViewController *detail = [[DetailViewController alloc] init];
    DetailModel *detailModel = [[DetailModel alloc] init];
    detailModel.id = model.myId;
    detail.model = detailModel;
    detail.otherDic = otherDic;
    [self.navigationController pushViewController:detail animated:YES];
    [self LabelMessageRead:model.myId];
}
#pragma mark - 这里标记消息已读（点击时）
- (void)LabelMessageRead:(NSString *)myId
{
    //设置单条消息已读  而不是所有
    NSString *getUrl = [NSString stringWithFormat:@"%@?infoId=%@", URL_SET_ALL_MSG_READED, myId];
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {

    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSString *str = [result objectForKey:@"msg"];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"回复： %@", str);
            
            //传送给服务器之后才跳转界面，此时应该插入一个动画 “正在同步服务器，请稍后”
            //[self.navigationController popViewControllerAnimated:YES];

        }
        else
        {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
        [fondView setBackgroundColor:[UIColor whiteColor]];

        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];
    }
    

}

#pragma mark - 获取用户id
- (void)getUserIdFromSever
{
    NSString *key = [GlobalMethod getApproveKey];
    NSString *device = [GlobalMethod GetIOSUUID];
    
    NSString *str =[NSString stringWithFormat:@"approveKey=%@&deviceParam=%@", device, key];
    NSString *getUrl = [NSString stringWithFormat:@"%@?%@", URL_USER_GETDETAIL, str];
    
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    if ([reach currentReachabilityStatus] != NotReachable) {
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:getUrl resultBlock:^(id result)
    {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = (NSDictionary *)result;
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
        if ([[dic objectForKey:@"msg"] isEqualToString:@"success"])
        {
            self.userId = [[dic objectForKey:@"obj"] objectForKey:@"id"];
            [self getMyData:self.userId];
//            [self getMyAnotherData:self.userId];
            
        }
        } else {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];

            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];

        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];
    }
}





#pragma mark - 修改：改成用户自己的Id 然后才能出现自己发布的消息，而不是所有人
//数据请求给我发布的数据
- (void)getMyData:(NSString *)userId
{
//    NSString *device = [GlobalMethod getApproveKey];
//    NSString *key = [GlobalMethod GetIOSUUID];
    //&sort=pub_time&order=desc&rid=c45ca002-3e9c-459f-9e38-8befdffa5db0
    NSString *str =[NSString stringWithFormat:@"approveKey=&deviceId=&page=0&rows=20&sort=pub_time&order=desc&rid=%@", userId];
    Reachability * reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];

    if ([reach currentReachabilityStatus] != NotReachable) {
    [AFNetWorkingYU netWorkWithURL:URL_GET_INFO_LIST body:str resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {

        NSMutableArray *marray = [NSMutableArray array];
        NSDictionary *bigDic = (NSDictionary *)result;
        
        
        [LoadIndicator stopAnimationInView:self.view];
        
        self.myDynamic.tableOther = [bigDic objectForKey:@"other"];
        NSLog(@"%@", self.myDynamic.tableOther);
        NSArray *array = [bigDic objectForKey:@"dataGrid"];
        for (NSDictionary *dic in array) {
            for (NSString *key in dic.allKeys) {
                if ([[dic objectForKey:key] isKindOfClass:[NSNull class]]) {
                    [dic setValue:@"" forKey:key];
                }
            }
            
            
            MyDynamicModel *model = [[MyDynamicModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            
            //拼接头像图片
            NSString *url = [dic objectForKey:@"puberImg"];
            NSString *strUrl = [NSString stringWithFormat:@"http://www.isu.so/attached/u_img/%@", url];
            model.puberImg = strUrl;
            
            //修改title
            NSString *myTitle = [dic objectForKey:@"title"];
            model.title = myTitle;
            
            //未读消息
            NSNumber *msg = [dic objectForKey:@"unreadMsg"];
            NSString *myMsg = [NSString stringWithFormat:@"%@", msg];
            model.myUnreadMsg = myMsg;
            
            //获取id
            NSString *myId = [dic objectForKey:@"id"];
            model.myId = myId;
            
            [marray addObject:model];
        }
        self.myDynamic.tableArray = marray;
            
        }
        else
        {
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];

            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
    }];
    }
    else
    {
        UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        [fondView setBackgroundColor:[UIColor whiteColor]];
        
        [self.view addSubview:fondView];
        [LoadIndicator networkStateNotReachableInView:fondView];
    }
}
//数据请求给我参与的数据
- (void)getMyAnotherData:(NSString *)userId
{
    NSString *myUrl = [NSString stringWithFormat:@"http://www.isu.so/user/joined?userId=%@", userId];
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:myUrl resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
        NSMutableArray *marray = [NSMutableArray array];
        NSDictionary *bigDic = (NSDictionary *)result;
        NSString *str = [result objectForKey:@"msg"];
        str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
        
        NSArray *array = [bigDic objectForKey:@"obj"];
        for (NSDictionary *dic in array) {
            MyDynamicModel *model = [[MyDynamicModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            
            //拼接头像图片
            NSString *url = [dic objectForKey:@"puberImg"];
            NSString *strUrl = [NSString stringWithFormat:@"http://www.isu.so/attached/u_img/%@", url];
            model.puberImg = strUrl;
            
            //修改title
            NSString *myTitle = [self filterHTML:[dic objectForKey:@"title"]];
            model.title = myTitle;
            
            //未读消息
            NSNumber *msg = [dic objectForKey:@"unreadMsg"];
            NSString *myMsg = [NSString stringWithFormat:@"%@", msg];
            model.myUnreadMsg = myMsg;
            
            //获取id
            NSString *myId = [dic objectForKey:@"id"];
            model.myId = myId;
            
            
            
            [marray addObject:model];
        }
        self.myDynamic.anotherArray = marray;
        } else {
            
            UIView *fondView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
            [fondView setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:fondView];
            [LoadIndicator networkStateNotReachableInView:fondView];
        }
        
    }];
}
#pragma mark - 去掉html的标签
-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}

- (void)viewWillAppear:(BOOL)animated
{
    if (self.myDynamic) {
        [self getUserIdFromSever];
    }
    else
    {
        [LoadIndicator addIndicatorInView:self.view];
    }
}

- (void)myLeftButtonAction:(id)sender
{
    YRSideViewController * sideview = [YRSideViewController share];
    sideview.needSwipeShowMenu= YES;
    if (sideview.rootViewController.view.frame.origin.x == 0) {
        [sideview showLeftViewController:YES];
        [sideview.rootViewController.view setFrame:CGRectMake(SCREEN_WIDTH/3*2, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    else
    {
        [sideview.rootViewController.view setFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
